/**
 * 插件市场JavaScript
 */
class PluginMarketManager {
    constructor() {
        this.baseUrl = '/adminapi/plugin';
        this.currentPage = 1;
        this.pageSize = 20;
        this.searchKeyword = '';
        this.currentCategory = '';
        this.currentPriceType = '';
        this.userToken = null;
        this.isLoggedIn = false;
        this.init();
    }

    /**
     * 初始化
     */
    init() {
        this.checkLoginStatus();
        this.bindEvents();
        this.loadPlugins();
    }

    /**
     * 检查登录状态
     */
    async checkLoginStatus() {
        try {
            const response = await fetch(`${this.baseUrl}/auth/checkLogin`);
            const data = await response.json();
            
            if (data.code === 1 && data.data.is_login) {
                this.isLoggedIn = true;
                this.userToken = data.data.user_info.token;
                this.showUserInfo(data.data.user_info);
            } else {
                this.isLoggedIn = false;
                this.showLoginForm();
            }
        } catch (error) {
            console.error('检查登录状态失败:', error);
            this.showLoginForm();
        }
    }

    /**
     * 显示登录表单
     */
    showLoginForm() {
        const loginSection = document.getElementById('loginSection');
        if (loginSection) {
            loginSection.innerHTML = `
                <div class="login-form">
                    <h5>登录插件市场</h5>
                    <div class="row">
                        <div class="col-md-3">
                            <input type="email" class="form-control" placeholder="邮箱" id="loginEmail">
                        </div>
                        <div class="col-md-3">
                            <input type="password" class="form-control" placeholder="密码" id="loginPassword">
                        </div>
                        <div class="col-md-2">
                            <button class="btn btn-primary" onclick="window.marketManager.login()">登录</button>
                        </div>
                        <div class="col-md-2">
                            <button class="btn btn-outline-secondary" onclick="window.marketManager.showRegister()">注册</button>
                        </div>
                    </div>
                </div>
            `;
        }
    }

    /**
     * 显示用户信息
     */
    showUserInfo(userInfo) {
        const loginSection = document.getElementById('loginSection');
        if (loginSection) {
            loginSection.innerHTML = `
                <div class="user-info">
                    <span>欢迎，<strong>${userInfo.name || userInfo.email}</strong></span>
                    <button class="btn btn-sm btn-outline-secondary" onclick="window.marketManager.logout()">退出</button>
                </div>
            `;
        }
    }

    /**
     * 绑定事件
     */
    bindEvents() {
        // 搜索框
        const searchInput = document.getElementById('searchInput');
        if (searchInput) {
            searchInput.addEventListener('input', (e) => {
                this.searchKeyword = e.target.value;
                this.debounceSearch();
            });
        }

        // 分类筛选
        const categorySelect = document.getElementById('categorySelect');
        if (categorySelect) {
            categorySelect.addEventListener('change', (e) => {
                this.currentCategory = e.target.value;
                this.loadPlugins(1);
            });
        }

        // 价格筛选
        const priceSelect = document.getElementById('priceSelect');
        if (priceSelect) {
            priceSelect.addEventListener('change', (e) => {
                this.currentPriceType = e.target.value;
                this.loadPlugins(1);
            });
        }
    }

    /**
     * 防抖搜索
     */
    debounceSearch() {
        clearTimeout(this.searchTimeout);
        this.searchTimeout = setTimeout(() => {
            this.loadPlugins(1);
        }, 500);
    }

    /**
     * 加载插件列表
     */
    async loadPlugins(page = 1) {
        try {
            this.currentPage = page;
            this.showLoading();

            const params = new URLSearchParams({
                page: page,
                limit: this.pageSize
            });

            if (this.searchKeyword) {
                params.append('keyword', this.searchKeyword);
            }
            if (this.currentCategory) {
                params.append('category', this.currentCategory);
            }
            if (this.currentPriceType) {
                params.append('price_type', this.currentPriceType);
            }

            const response = await fetch(`${this.baseUrl}/market/getPlugins?${params}`);
            const data = await response.json();

            if (data.code === 1) {
                this.renderPlugins(data.data.plugins || data.data.list || []);
                this.renderPagination(data.data.pagination);
            } else {
                this.showError('加载插件失败: ' + (data.msg || '未知错误'));
            }
        } catch (error) {
            console.error('加载插件失败:', error);
            this.showError('连接插件市场失败，请检查网络连接或稍后重试');
        }
    }

    /**
     * 渲染插件列表
     */
    renderPlugins(plugins) {
        const container = document.getElementById('pluginList');
        if (!container) return;

        if (plugins.length === 0) {
            container.innerHTML = `
                <div class="empty-state">
                    <div class="icon">🔍</div>
                    <h3>没有找到插件</h3>
                    <p>尝试调整搜索条件或浏览其他分类</p>
                </div>
            `;
            return;
        }

        const html = plugins.map(plugin => {
            const price = plugin.price?.basic || plugin.price || 0;
            const premiumPrice = plugin.price?.premium || 0;
            let priceText = price > 0 ? `¥${price}` : '免费';
            if (premiumPrice > 0 && premiumPrice !== price) {
                priceText += ` - ¥${premiumPrice}`;
            }

            const isPurchased = plugin.is_purchased || false;
            const downloadText = isPurchased ? '下载' : (price > 0 ? '购买' : '下载');

            return `
                <div class="col-md-4 col-lg-3 mb-4">
                    <div class="card plugin-card h-100">
                        <div class="position-relative">
                            <img src="${plugin.image || '/static/images/default-plugin.png'}" 
                                 class="card-img-top plugin-image" alt="${plugin.name}">
                            <span class="price-tag ${price > 0 ? 'paid' : 'free'}">${priceText}</span>
                            ${isPurchased ? '<span class="purchased-badge">已购买</span>' : ''}
                        </div>
                        <div class="card-body d-flex flex-column">
                            <h5 class="card-title">${plugin.name}</h5>
                            <p class="card-text flex-grow-1">${plugin.description}</p>
                            <div class="plugin-meta">
                                <small class="text-muted">作者: ${plugin.author}</small>
                                <small class="text-muted">下载: ${plugin.downloads || 0}</small>
                            </div>
                            <div class="plugin-actions mt-2">
                                <button class="btn btn-primary btn-sm" onclick="window.marketManager.showPluginDetail('${plugin.id}')">
                                    查看详情
                                </button>
                                <button class="btn btn-success btn-sm" onclick="window.marketManager.downloadPlugin('${plugin.id}')">
                                    ${downloadText}
                                </button>
                            </div>
                        </div>
                    </div>
                </div>
            `;
        }).join('');

        container.innerHTML = html;
    }

    /**
     * 渲染分页
     */
    renderPagination(pagination) {
        const container = document.getElementById('pagination');
        if (!container || !pagination) return;

        if (pagination.total_pages <= 1) {
            container.innerHTML = '';
            return;
        }

        let html = '';
        const currentPage = pagination.current_page;
        const totalPages = pagination.total_pages;

        // 上一页
        if (currentPage > 1) {
            html += `<li class="page-item"><a class="page-link" href="#" onclick="window.marketManager.loadPlugins(${currentPage - 1})">上一页</a></li>`;
        }

        // 页码
        const startPage = Math.max(1, currentPage - 2);
        const endPage = Math.min(totalPages, currentPage + 2);

        for (let i = startPage; i <= endPage; i++) {
            const activeClass = i === currentPage ? 'active' : '';
            html += `<li class="page-item ${activeClass}"><a class="page-link" href="#" onclick="window.marketManager.loadPlugins(${i})">${i}</a></li>`;
        }

        // 下一页
        if (currentPage < totalPages) {
            html += `<li class="page-item"><a class="page-link" href="#" onclick="window.marketManager.loadPlugins(${currentPage + 1})">下一页</a></li>`;
        }

        container.innerHTML = html;
    }

    /**
     * 显示加载状态
     */
    showLoading() {
        const container = document.getElementById('pluginList');
        if (container) {
            container.innerHTML = `
                <div class="loading-state">
                    <div class="spinner-border" role="status">
                        <span class="visually-hidden">加载中...</span>
                    </div>
                    <p>正在加载插件...</p>
                </div>
            `;
        }
    }

    /**
     * 显示错误信息
     */
    showError(message) {
        const container = document.getElementById('pluginList');
        if (container) {
            container.innerHTML = `
                <div class="error-state">
                    <div class="icon">⚠️</div>
                    <h3>加载失败</h3>
                    <p>${message}</p>
                    <button class="btn btn-primary" onclick="window.marketManager.loadPlugins()">重试</button>
                </div>
            `;
        }
    }

    /**
     * 用户登录
     */
    async login() {
        const email = document.getElementById('loginEmail').value;
        const password = document.getElementById('loginPassword').value;

        if (!email || !password) {
            alert('请输入邮箱和密码');
            return;
        }

        try {
            const response = await fetch(`${this.baseUrl}/auth/login`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({ email, password })
            });

            const data = await response.json();

            if (data.code === 1) {
                this.isLoggedIn = true;
                this.userToken = data.data.token;
                this.showUserInfo(data.data.user);
                this.loadPlugins(); // 重新加载以显示购买状态
                
                // 清空登录表单
                document.getElementById('loginEmail').value = '';
                document.getElementById('loginPassword').value = '';
            } else {
                alert('登录失败: ' + data.msg);
            }
        } catch (error) {
            console.error('登录失败:', error);
            alert('登录失败');
        }
    }

    /**
     * 用户退出
     */
    async logout() {
        try {
            await fetch(`${this.baseUrl}/auth/logout`, {
                method: 'POST'
            });
        } catch (error) {
            console.error('退出失败:', error);
        }

        this.isLoggedIn = false;
        this.userToken = null;
        this.showLoginForm();
        this.loadPlugins(); // 重新加载
    }

    /**
     * 显示插件详情
     */
    async showPluginDetail(pluginId) {
        // 这里可以实现插件详情弹窗
        console.log('显示插件详情:', pluginId);
    }

    /**
     * 下载插件
     */
    async downloadPlugin(pluginId) {
        if (!this.isLoggedIn) {
            alert('请先登录');
            return;
        }

        try {
            const response = await fetch(`${this.baseUrl}/download/downloadPlugin`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({ plugin_id: pluginId })
            });

            const data = await response.json();

            if (data.code === 1) {
                alert('下载成功!');
            } else {
                alert('下载失败: ' + data.msg);
            }
        } catch (error) {
            console.error('下载失败:', error);
            alert('下载失败');
        }
    }
}

// 页面加载完成后初始化
document.addEventListener('DOMContentLoaded', () => {
    window.marketManager = new PluginMarketManager();
});

// 确保在全局作用域中可用
window.PluginMarketManager = PluginMarketManager;
